// pages/goods_list/index.js

import { api } from '../../request/index.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: '综合',
        isActive: true,
      },
      {
        id: 1,
        value: '销量',
        isActive: false,
      },
      {
        id: 2,
        value: '价格',
        isActive: false,
      },
    ],

    // 商品列表
    goodsList: [],
  },
  // 查询参数
  queryParams: {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10,
  },
  // 总页数
  totalPages: 1,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.queryParams.cid = options.cid
    this.getList()
  },
  // tab切换事件
  currentClick: function (e) {
    let { index } = e.detail
    let { tabs } = this.data
    tabs.forEach((v, i) =>
      i === index ? (v.isActive = true) : (v.isActive = false)
    )
    this.setData({
      tabs,
    })
  },
  // 获取列表
  async getList() {
    const res = await api({ url: '/goods/search', data: this.queryParams })
    // 总条数
    const total = res.message.total
    this.totalPages = Math.ceil(total / this.queryParams.pagesize)
    this.setData({
      goodsList: [...this.data.goodsList, ...res.message.goods],
    })
    // 关闭下拉刷新窗口
    wx.stopPullDownRefresh()
  },
  // 滚动条触底事件(上划加载下一页)
  onReachBottom() {
    if (this.queryParams.pagenum >= this.totalPages) {
      wx.showToast({
        title: '没有下一页数据',
      })
    } else {
      this.queryParams.pagenum++
      this.getList()
    }
  },
  // 下拉刷新
  onPullDownRefresh(){
    this.setData({
      goodsList:[]
    })
    this.queryParams.pagenum = 1
    this.getList();
  }
})
